<?php

namespace app\modules\index\services;

use app\common\services\BaseService;
use app\components\pagination\Pagination;
use app\config\Constants;
use app\models\Merchant;
use app\models\MerchantCategoryRelation;
use app\utils\CoordinateUtil;
use yii\helpers\ArrayHelper;

/**
 * 搜索服务
 * Class SearchService
 * @package app\modules\index\services
 */
class SearchService extends BaseService{

    private const SELECT = ['merchant_id','merchant_name','merchant_desc','thumbnail','customer_type','business_time','delivery_type','lng_lat'];

    public static function merchant($name,$cat_id,$lng_lat,&$page,$pagesize)
    {
        $query = Merchant::find()
            ->select(self::SELECT)
            ->orderBy(['sort'=>SORT_ASC])
            ->asArray(true)
            ->andWhere(['is_show'=>2])
            ->andWhere(['status'=>Constants::STATUS_NORMAL]);

        //聚合商品和商户名搜索
        if(!empty($name)){
            $query->andWhere(['like','merchant_name',$name]);
            $query->orWhere(['in','merchant_id',ArrayHelper::getColumn(GoodsService::search(null,$name),"merchant_id")]);
        }
        if(!empty($cat_id)){
            $cat_ids = [$cat_id];
            //查询子分类
            $child_list = MerchantCategoryService::getList($cat_id);
            if(!empty($child_list)){
                $cat_ids = array_merge($cat_ids,ArrayHelper::getColumn($child_list,"cat_id"));
            }
            $merchant_ids = MerchantCategoryRelation::find()->select("merchant_id")->where(['in','cat_id',$cat_ids])->column();
            $query->andWhere(['in','merchant_id',$merchant_ids]);
        }

        $page = new Pagination(['totalCount' => $query->count(), 'pageSize' => $pagesize]);
        $query->offset($page->getOffset());
        $query->limit($page->getLimit());

        $data = $query->all();

        //设置营业标记和距离和配送规则
        foreach($data as $k=>$v){
            $range = explode("-",$v['business_time']);
            $data[$k]['business_status'] =  date("H") >= $range[0] && date("H") <= $range[1] ? 2 : 1;

            if(!empty($v['lng_lat']) && !empty($lng_lat)){
                $lng_lat1 = explode(",",$v['lng_lat']);
                $lng_lat2 = explode(',',$lng_lat);
                $data[$k]['distance'] = CoordinateUtil::distance($lng_lat1[0],$lng_lat1[1],$lng_lat2[0],$lng_lat2[1],CoordinateUtil::KILOMETER);
            }
        }

        return $data;
    }
}